package com.cskaoyan.advice;


import com.cskaoyan.bean.po.MarketAdmin;
import com.cskaoyan.bean.po.MarketLog;
import com.cskaoyan.service.adminservice.LogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
public class LogAspectJAdvice {
    @Autowired
    LogService logService;
    @Autowired
    HttpServletRequest request;

    @Pointcut("@annotation(com.cskaoyan.annotation.ExecutionLog)")
    public void methodPointcut() {
    }
    @Pointcut("execution(* com..service..*(..))")
    public void pointcut1() {
    }



    // @Around(" pointcut1()")
    public Object executeLog(ProceedingJoinPoint joinPoint ) throws Throwable {


        //获得委托类对象
        Object target = joinPoint.getTarget();
        System.out.println("around:" + target.getClass().getName());
        if (target instanceof LogService) {
            return joinPoint.proceed();
        }

        //获得 委托类 类名
        String simpleName = joinPoint.getTarget().getClass().getSimpleName();
        //获得 委托类 方法 名称
        String name = joinPoint.getSignature().getName();
        //要插入的具体操作字段
        String operation = simpleName + "." + name;
        boolean success = true;
        String errMsg = null;
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            success = false;
            errMsg = throwable.getMessage();
            throwable.printStackTrace();
        } finally {
            Subject subject = SecurityUtils.getSubject();

            MarketAdmin marketAdmin = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
            String ip = request.getServerName();
            // Log log = new Log(null, operation, new Date(), success, errMsg);
            MarketLog marketLog = new MarketLog(null, marketAdmin.getUsername(), ip, 1, operation, success, null, errMsg, new Date(), new Date(), true);
            logService.createLog(marketLog);
        }
        return proceed;
    }

}
